<template>
  <div class="system-management-container app-container">
    <div class="search-box">
      <TabSearch
        label-width="90px"
        :data="searchData"
        @searchForm="searchForm"
        @resetForm="resetForm"
      />
    </div>
    <div class="list-wrapper" style="flex: 1;">
      <div class="content">
        <div class="title">
          <span>角色管理</span>
        </div>
        <div class="operation">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <!-- <el-button @click="handleEdit">修改</el-button> -->
          <el-button @click="openDelectBox('pk_id')">删除</el-button>
          <el-button @click="openExportBox">导出</el-button>
        </div>
        <comm-table
          ref="dragTable"
          :loading="loading"
          :data="tableData"
          @selectionChange="selectionChange"
          style="width: 100%"
        >
          <el-table-column width="80" type="selection" />
          <el-table-column prop="role_name" label="角色名称" width="150" />
          <el-table-column prop="role_code" label="权限字符" width="150" />
          <el-table-column prop="role_sort" label="显示顺序" width="150" />
          <el-table-column prop="status" label="状态" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '0'">正常</span>
              <span v-else-if="scope.row.status === '1'">停用</span>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="250" show-overflow-tooltip />
          <el-table-column label="操作" width="220">
            <template slot-scope="scope">
              <span class="operation-btn" @click="handleEdit(scope)">编辑</span>
              <span class="operation-btn" @click="handleJurisdiction(scope.row.pk_id)">数据权限</span>
              <span class="operation-btn" @click="openDelectBox({ ids: scope.row.pk_id })">删除</span>
            </template>
          </el-table-column>
        </comm-table>
      </div>
    </div>
    <!-- 新增、编辑角色 -->
    <div v-if="dialogVisible">
      <el-dialog
        :title="title + '角色'"
        :visible.sync="dialogVisible"
        width="50%"
        class="handle-dialog"
        :destroy-on-close="true"
        @close="dialogVisible = false"
      >
        <!-- @handleCancel="handleCancel"
        @handleConfirm="handleConfirm"-->
        <add-role ref="addDialog" :titles="title" />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleConfirm">确定</el-button>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 角色权限 -->
    <div v-if="jurisdictionDialogVisible">
      <el-dialog
        title="分配数据权限"
        :visible.sync="jurisdictionDialogVisible"
        width="50%"
        class="handle-dialog"
        :destroy-on-close="true"
        @close="jurisdictionDialogVisible = false"
      >
        <role-Jurisdiction ref="jurisdictionDialog" :title="title" />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmSaveRule">确定</el-button>
          <el-button @click="jurisdictionDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TabSearch from "@/components/TabSearch";
import AddRole from "../modules/addRole";
import RoleJurisdiction from "../modules/roleJurisdiction";
import TableCommMixin from "@/mixins/TableCommMixin";
import { getAction } from '@/api/manage'
import {
  getRoleDetail, // 详情
  handleSaveRule, // 数字权限
  getRoleMenuTreeData // 由角色id获取对应菜单树
} from "@/api/api";
export default {
  name: "RoleManagement",
  components: {
    TabSearch,
    AddRole,
    RoleJurisdiction
  },
  mixins: [TableCommMixin],
  data() {
    return {
      title: "",
      dialogVisible: false,
      jurisdictionDialogVisible: false,
      url: {
        list: "/system/api/Role",
        method: "get",
        // 新增
        add: "/system/api/Role",
        addMethod: "post",
        // 编辑
        edit: "/system/api/Role",
        editMethod: "put",
        // 删除
        delete: "/system/api/Role",
        deleteMethod: "delete",
        // 导出
        export: "/system/api/Role/Export"
      },
      searchData: [
        {
          key: "role_name",
          title: "角色名称 ",
          type: "input",
          attr: {
            placeholder: "请输入"
          }
        },
        {
          key: "create_time",
          title: "创建时间",
          type: "time",
          attr: {
            placeholder: "请选择"
          }
        },
        // {
        //   key: 'userStatus',
        //   title: '角色状态',
        //   type: 'arrow',
        //   attr: {
        //     placeholder: '所有'
        //   }
        // },
        {
          key: "status",
          title: "角色状态",
          type: "select",
          attr: {
            placeholder: "所有"
          },
          options: [
            {
              value: "",
              label: "所有"
            },
            {
              value: 0,
              label: "正常"
            },
            {
              value: 1,
              label: "停用"
            }
          ]
        },
        {
          key: "role_code",
          title: "权限字符",
          type: "input",
          attr: {
            placeholder: "请输入"
          }
        }
      ]
    };
  },
  methods: {
    // 删除
    openDelectBox(param) {
      this.$confirm("此操作将此用户删除吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (typeof param === "string") {
            this.handleDelete(param);
          } else {
            this.handleDeleteOne(param);
          }
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除"
          });
        });
    },
    openExportBox() {
      this.$confirm("确定导出数据至EXCEL吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.handleExport();
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消导出"
          });
        });
    },
    // 编辑之前
    async beforeEdit(data) {
      let arr = [];
      await getRoleMenuTreeData({ roleId: data.row.pk_id }).then(res => {
        if (res.code === 0) {
          arr = res.data.filter(item => {
            return item.checked === true;
          });
        }
      });
      return new Promise((resolve, reject) => {
        getRoleDetail({ pid: data.row.pk_id }).then(res => {
          if (res.code === 0) {
            // 唯一性检测
            if (!res.data["checkParam"]) {
              res["data"]["checkParam"] = {
                uniqueRoleName: false,
                uniqueRoleCode: false
              };
            }
            // 菜单数据默认选中
            if (arr.length) {
              res.data["menuIds"] = arr.map(ite => ite.id);
            }
            console.log(res.data);
            resolve(res.data);
          } else {
            this.$message({ type: "error", message: res.msg });
            reject({});
          }
        });
      });
    },
    // 提交之前
    async beforeSubmit(data) {
      return new Promise(resolve => {
        let adoptValue = false;
        // 唯一性检测
        if (data["checkParam"]) {
          if (Object.values(data["checkParam"]).length) {
            Object.values(data["checkParam"]).some(item => {
              if (item) {
                adoptValue = true;
              }
            });
          }
        }
        if (data["menuIds"] instanceof Array && data["menuIds"].length) {
          data["menuIds"] = data["menuIds"].join(",");
          if (this.action == "add") {
            this.url.add = "/system/api/Role" + "?menuIds=" + data["menuIds"];
          } else if (this.action == "edit") {
            this.url.edit = "/system/api/Role" + "?menuIds=" + data["menuIds"];
          }
        }
        if (adoptValue) {
          resolve({ status: -1 });
        } else {
          resolve(data);
        }
      });
    },
    // 数字权限-获取
    handleJurisdiction(id) {
      this.jurisdictionDialogVisible = true;
      getRoleDetail({ pid: id }).then(res => {
        if (res.code === 0) {
          this.$nextTick(() => {
            setTimeout(() => {
              this.$refs["jurisdictionDialog"]["form"] = JSON.parse(
                JSON.stringify(res.data)
              );
            }, 200);
          });
        }
      });
    },
    // 数字权限-确认
    confirmSaveRule() {
      let param = this.$refs["jurisdictionDialog"]["form"];
      this.jurisdictionDialogVisible = false;
      // let url = "/system/api/Role/SaveRule";
      // if (param.deptIds instanceof Array && param.deptIds.length) {
      //   url = url + `?deptIds=${param.deptIds.join(",")}`;
      //   delete param.deptIds
      // }
      // console.log(param, "confirmSaveRule");
      // getAction(url, param).then(res => {
      //   if (res.code === 0) {
      //     this.$message.success(res.msg);
      //     this.getList();
      //   } else {
      //     this.$message.error(res.msg);
      //   }
      // });
      handleSaveRule(param).then(res => {
        if(res.code === 0) {
          this.$message.success(res.msg)
          this.getList();
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.system-management-container {
  margin: 0 22px;
  .search-box {
    margin-top: 20px;
    background: rgba(245, 247, 249, 1);
    border: 1px solid rgba(221, 221, 221, 1);
    padding-top: 13px;
  }
}
</style>
